package org.oschina.api.upload.service;

import java.util.List;
import org.oschina.Config;
import org.oschina.Constants;
import org.oschina.Module;
import org.oschina.api.BaseService;
import org.oschina.api.manage.config.service.ConfigService;
import org.oschina.api.upload.dao.UploadRecordDAO;
import org.oschina.api.upload.model.UploadRecord;
import org.oschina.api.upload.vo.UploadRecordVo;
import org.oschina.bean.Pager;
import org.oschina.api.index.service.IndexService;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UploadRecordService extends BaseService {

	@Autowired
	private UploadRecordDAO uploadRecordDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private ConfigService configService;
	
	/**
	 * 返回
	 * @param pn
	 * @return
	 */
	@Require(authorization=Module.MODULE_20)
	public Pager<UploadRecordVo> findVo(int pn)
	{
		Pager pager=new Pager(pn,getCount(),getPageCount(),null);
		if(pager.getData_sum()>0)
			pager.setData(findVo(pager.getStart(), pager.getPage_count()));
		
		return pager;
	}
	
	/**
	 * 创建
	 * @param name
	 * @param path
	 * @param size
	 * @param type
	 */
	public UploadRecord create(String name,String path,long size,String type)
	{
		UploadRecord uploadRecord=new UploadRecord();
		uploadRecord.setName(name);
		uploadRecord.setPath(path);
		uploadRecord.setSize(size);
		uploadRecord.setType(type);
		return create(uploadRecord);
	}
	
	/**
	 * 返回单页数量
	 * @return
	 */
	private int getPageCount()
	{
		return (Integer)configService.getValueById(Config.CONFIG_11, Integer.class);
	}
	
	/**
	 * 创建
	 * @param uploadRecord
	 * @return
	 */
	private UploadRecord create(UploadRecord uploadRecord)
	{
		uploadRecord.setId(getIndex());
		uploadRecord.setUpload_time(DateUtil.now());
		return uploadRecordDAO.create(uploadRecord);
	}
	
	/**
	 * 返回
	 * @param first
	 * @param max
	 * @return
	 */
	private List<UploadRecordVo> findVo(int first,int max)
	{
		return uploadRecordDAO.findVo(first, max);
	}
	
	/**
	 * 返回数量
	 * @return
	 */
	private int getCount()
	{
		return uploadRecordDAO.getCount();
	}
	
	private int getIndex()
	{
		return (Integer)indexService.getMajorById(Constants.INDEX_UPLOAD_RECORD);
	}
}